# -*- coding: utf-8 -*-
import sys, os
try:
        import pygtk
        pygtk.require("2.0")
except:
        pass
try:
        import gtk
        import gtk.glade
	import gobject
except:
        sys.exit(1)
rc_string = """
style "treeview-style" {
	GtkTreeView::odd-row-color = "#EEEEEE"
}
class "GtkTreeView" style "treeview-style"
"""
gtk.rc_parse_string(rc_string)
class Tree:
	def __init__(self, titles, menu_items, *args, **kwargs):
		global rc_string
		self.menu_items = menu_items
		self.titles = titles
                self.treestore = gtk.TreeStore(*args)
                self.treeview = gtk.TreeView(self.treestore)
                self.treeview.connect('button_press_event', self.button_handler)
                self.cell = gtk.CellRendererText()
                for i in range(len(titles)):
			if titles[i] != "INVISIBLE":
	                        a = gtk.TreeViewColumn(titles[i])
        	                a.pack_start(self.cell, True)
                	        a.add_attribute(self.cell,'text',i)
	                        a.set_resizable(True)
        	                a.set_reorderable(True)
                	        self.treeview.append_column(a)
				a.connect("clicked", self.column_clicked, i)
				a.set_clickable(True)
				a.set_property('sort-indicator', True)
				a.set_property("sort-order", gtk.SORT_ASCENDING)
                self.treeview.set_reorderable(True)
#		gtk.rc_reset_styles(treeview.get_settings())
#		gtk.rc_parse_string(rc_string)
#		print "odd-row-color = %s"%self.treeview.style_get_property('odd-row-color')
                self.treeview.show()
                self.widget = self.treeview
	
        def button_handler(self, treeview, event, data = None):
#                if event.button == 3:
                 var = treeview.get_path_at_pos(int(event.x), int(event.y))
                 if var != None:
 	                path, col, rel, rel = var
			iter = None
			for i in path:
				if iter == None:
					iter = self.treestore.get_iter_root()
				else:
					iter = self.treestore.iter_children(iter)
				for k in range(i):
					iter = self.treestore.iter_next(iter)

                        self.selected_rows = list()
			self.selected_iter = iter
			c = 0
			for i in self.titles:
				self.selected_rows.append(self.treestore.get_value(iter, c))
				c = c + 1
			if event.button == 3:
	                        menu = self.create_menu(None, None)
        	                menu.popup(None, None, None, event.button, event.time)

        def create_menu(self, window,event, data=None):
                item_factory = gtk.ItemFactory(gtk.Menu, "<main>", None)
                item_factory.create_items(self.menu_items)
                self.item_factory = item_factory
                return item_factory.get_widget("<main>")


	def setSortable(self, column_id = 0, direction = gtk.SORT_ASCENDING):
		self.treestore.set_sort_column_id(column_id,direction)

	def append(self, row, parent = None):
		return self.treestore.append(parent,row)

	def remove(self, iter):
		if self.treestore.iter_is_valid(iter):
			self.treestore.remove(iter)

	def update(self, iter, column_id, value):
		if self.treestore.iter_is_valid(iter):
			self.treestore.set(iter, column_id, value)

	def clear(self, *args, **kwargs):
		self.treestore.clear()

	def column_clicked(self, column, user_param):
		id, method = self.treestore.get_sort_column_id()
		smethod = gtk.SORT_ASCENDING
		if id == user_param:
			if method == gtk.SORT_DESCENDING:
				smethod = gtk.SORT_ASCENDING
			else:
				smethod = gtk.SORT_DESCENDING
		self.treestore.set_sort_column_id(user_param, smethod)

class QueueTree(Tree):
	def __init__(self, menu_items):
		self.titles = [_('File'),_('Status'),_('Size'),_('Priority'), _('Sources'), _('TTH'),"INVISIBLE"]
		self.menu_items = menu_items
		self.treestore = gtk.TreeStore(str, int,str,str, str, str,gobject.TYPE_INT64)
		self.treeview = gtk.TreeView(self.treestore)
		self.treeview.connect('button_press_event', self.button_handler)
		self.cell = gtk.CellRendererText()
		self.cellcombo = gtk.CellRendererCombo()
		self.cellprog = gtk.CellRendererProgress()
		columns = {}
		for i in (0, 2, 4, 5):
			a = gtk.TreeViewColumn(self.titles[i])
			a.pack_start(self.cell, True)
			a.add_attribute(self.cell, 'text', i)
			a.set_resizable(True)
			columns[i] = a
			a.connect("clicked", self.column_clicked, i)
                        a.set_property('sort-indicator', True)
                        a.set_property("sort-order", True)
			a.set_clickable(True)
#		self.treeview.append_column(a)
		a = gtk.TreeViewColumn(self.titles[1])
		a.pack_start(self.cellprog, True)
		a.add_attribute(self.cellprog, 'value', 1)
		a.set_resizable(True)
		a.set_min_width(100)
#		self.treeview.append_column(a)
		self.list_store = gtk.ListStore(str)
		for i in range(0,11):
			self.list_store.append([i])
#		
		a.set_clickable(True)
                a.set_property('sort-indicator', True)
                a.set_property("sort-order", True)

		a.connect("clicked", self.column_clicked, 1)
		columns[1] = a
		a = gtk.TreeViewColumn(self.titles[3])
		a.pack_start(self.cell, True)
		a.add_attribute(self.cell, 'text', 3)
		columns[3] = a
                a.set_property('sort-indicator', True)
                a.set_property("sort-order", True)
		a.set_clickable(True)
		a.connect("clicked", self.column_clicked, 3)
		for i in range(0,6):
			self.treeview.append_column(columns[i])
#		self.treeview.append_column(a)
		self.treestore.set_sort_func(2, self._sort_func, None)
		self.treeview.show()
		self.widget = self.treeview

        def _sort_func(self, treemodel, iter1, iter2, data = None):
                first = self.treestore.get_value(iter1, 6)
                second = self.treestore.get_value(iter2, 6)
                if first > second:
                        return 1
                elif first < second:
                        return -1
                else:
                        return 0

class FileListTree(Tree):
	def __init__(self, menu_items):
		# Initialize objects.
		self.titles = ['',_('File'), _('Size'),_('TTH'), 'INVISIBLE']
		self.menu_items = menu_items
		self.treestore = gtk.TreeStore(gtk.gdk.Pixbuf, str, str, str, gobject.TYPE_INT64)
		self.treestore.set_sort_func(2, self._sortsize, None)
		self.treestore.set_sort_func(1, self._sortname, None)
		self.treeview = gtk.TreeView(self.treestore)
		self.celltext = gtk.CellRendererText()
		self.cellpix = gtk.CellRendererPixbuf()
                self.treeview.connect('button_press_event', self.button_handler)
		# Add columns
		column = gtk.TreeViewColumn(self.titles[0])
		column.pack_start(self.cellpix, True)
		column.add_attribute(self.cellpix, 'pixbuf', 0)
		column.set_resizable(False)
		column.set_clickable(True)
		column.set_property('sort-indicator', True)
		column.set_property('sort-order', True)
		column.connect('clicked', self.column_clicked, 0)
		self.treeview.append_column(column)
		for i in range(1, 4):
 	                column = gtk.TreeViewColumn(self.titles[i])
        	        column.pack_start(self.celltext, True)
                	column.add_attribute(self.celltext, 'text', i)
	                column.set_resizable(True)
        	        column.set_clickable(True)
                	column.set_property('sort-indicator', True)
	                column.set_property('sort-order', True)
        	        column.connect('clicked', self.column_clicked, i)
			self.treeview.append_column(column)
		self.treeview.show()
		self.widget = self.treeview

        def _sortsize(self, treemodel, iter1, iter2, data = None):
                first = self.treestore.get_value(iter1, 4)
                second = self.treestore.get_value(iter2, 4)
                if first > second:
                        return 1
                elif first < second:
                        return -1
                else:
                        return 0

	def _sortname(self, treemodel, iter1, iter2, data = None):
		size1 = self.treestore.get_value(iter1, 4)
		size2 = self.treestore.get_value(iter2, 4)
		name1 = self.treestore.get_value(iter1, 1)
		name2 = self.treestore.get_value(iter2, 1)
		if (size1 == -1 and size2 == -1) or (size1 > 0 and size2 > 0):
			# Two folders of files
			if name1 > name2:
				return 1
			elif name1 < name2:
				return -1
			else:
				return 0
		elif size1 == -1 and size2 > 0:
			# First -- folder, second -- file
			return 1
		elif size1 > 0 and size2 == -1:
			# First -- file, second -- folder
			return -1


class ConnectionsTree(Tree):
	def __init__(self, menu_items):
		self.titles = ['',_('Status'),_('Speed'),_('File'),_('User'),_('TTH'),'CID']
		self.menu_items = menu_items
		self.treestore = gtk.TreeStore(str, int, str, str, str, str, int)
		self.treeview = gtk.TreeView(self.treestore)
		self.treeview.connect('button_press_event', self.button_handler)
		self.cell = gtk.CellRendererText()
		self.cellpix = gtk.CellRendererPixbuf()
		self.cellprog = gtk.CellRendererProgress()
		a = gtk.TreeViewColumn(self.titles[0])
		a.pack_start(self.cellpix, True)
		a.add_attribute(self.cellpix, 'stock-id', 0)
		a.set_resizable(False)
		a.set_clickable(True)
                a.set_property('sort-indicator', True)
                a.set_property("sort-order", True)
		a.connect("clicked", self.column_clicked, 0)
		self.treeview.append_column(a)
		a = gtk.TreeViewColumn(self.titles[1])
		a.pack_start(self.cellprog, True)
		a.add_attribute(self.cellprog, 'value', 1)
		a.set_resizable(True)
		a.set_clickable(True)
                a.set_property('sort-indicator', True)
                a.set_property("sort-order", True)
		a.set_min_width(100)
		a.connect("clicked", self.column_clicked, 1)
		self.treeview.append_column(a)
		for i in range(2, 6):
			a = gtk.TreeViewColumn(self.titles[i])
			a.pack_start(self.cell, True)
			a.add_attribute(self.cell, 'text', i)
			a.set_resizable(True)
			a.connect("clicked", self.column_clicked, i)
			a.set_clickable(True)
                        a.set_property('sort-indicator', True)
                        a.set_property("sort-order", True)
			self.treeview.append_column(a)
		self.treeview.show()
		self.widget = self.treeview
		
class NickListTree(Tree):
	def __init__(self,*args, **kwargs):
		Tree.__init__(self, *args, **kwargs)
#		self.setSortable(0)
		

class FavoritesTree(Tree):
        def __init__(self, menu_items):
                self.menu_items = menu_items
                titles = [_('Hub name'), _('Autoconnect')]
		self.titles = titles
                self.treestore = gtk.TreeStore(str, bool)
                self.treeview = gtk.TreeView(self.treestore)
                self.treeview.connect('button_press_event', self.button_handler)
                self.cell = gtk.CellRendererText()
#               for i in range(len(titles)):
                a = gtk.TreeViewColumn(titles[0])
                a.pack_start(self.cell, True)
                a.add_attribute(self.cell,'text',0)
                a.set_resizable(True)
                a.set_reorderable(True)
		a.set_min_width(300)
                self.treeview.append_column(a)
		a = gtk.TreeViewColumn(titles[1])
		self.celltoggle = gtk.CellRendererToggle()
		self.celltoggle.connect("toggled", self.toggled)
		a.pack_start(self.celltoggle, True)
		a.add_attribute(self.celltoggle, 'active',1)
		a.set_resizable(True)
		a.set_reorderable(True)
		self.treeview.append_column(a)
                self.treeview.set_reorderable(True)
                self.treeview.show()
                self.widget = self.treeview

	def _save(self, filename):
		filed = open(filename, 'w')
		filed.write('<Favorites>\n')
		iter = self.treestore.get_iter_root()
		while iter != None:
			values = self.treestore.get(iter,0,1)
			server = values[0].strip()
			if values[1]:
				autoconnect = 1
			else:
				autoconnect = 0
			filed.write("  <p name=\"%s\">%s</p>\n"%(server, autoconnect))
			iter = self.treestore.iter_next(iter)
		filed.write('</Favorites>')
		filed.close()
	def Rows(self):
		iter = self.treestore.get_iter_root()
		while iter != None:
			values = list()
			for i in range(0, len(self.titles)):
				values.append(self.treestore.get_value(iter, i))
			yield values
			iter = self.treestore.iter_next(iter)
			
	def toggled(self, *args, **kwargs):
		#print "Toggled!", self.selected_rows	
		self.treestore.set_value(self.selected_iter, 1, not self.selected_rows[1])
